/*
 * Copyright (c) 2013.
 * 游戏服务器核心代码编写人陈磊拥有使用权
 * 联系方式：E-mail:13638363871@163.com ;qq:502959937
 * 个人博客主页：http://my.oschina.net/chenleijava
 */

package com.dc.gameserver.extComponents.utilsKit;

import com.google.protobuf.Message;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * @author 石头哥哥
 *         Date: 13-11-9</br>
 *         Time: 下午12:31</br>
 *         Package: Server.ExtComponents.RedisManager</br>
 *         注解：采用 protoBuffer来序列号化  ,将messageLite封装为byte[]
 *        注意  pb实体类型对象本身已经实现了序列化接口，并且可以在byte[]于对象直接转化
 */
public class ProtoBufferRedisSerializer implements RedisSerializer<Message> {

    /**
     *序列化的对象类
     */
   private final  Message Message;

   public ProtoBufferRedisSerializer(Message Message){
       this.Message = Message;
   }

    /**
     * Serialize the given object to binary data.
     *
     * @param Message object to serialize
     * @return the equivalent binary data
     */
    @Override
    public byte[] serialize(Message Message) throws SerializationException {
        return Message.toByteArray();
    }
    /**
     * Deserialize an object from the given binary data.
     *
     * @param bytes object binary representation
     * @return the equivalent object instance
     */
    @Override
    public Message deserialize(byte[] bytes) throws SerializationException {
        try {
            return this.Message.getParserForType().parseFrom(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[]args){
//        RedisSerializer<Message> generatedMessageRedisSerializer=new ProtoBufferRedisSerializer(testVo.getDefaultInstance());
//        testVo.Builder builder=testVo.newBuilder();
//        builder.setCardCount(1) ;
//        builder.setCardNum(1);
//        byte[]mesage=generatedMessageRedisSerializer.serialize(builder.build());
//
//        testVo m= (testVo) generatedMessageRedisSerializer.deserialize(mesage);
//
//        System.out.println(m.getCardCount());

    }
}
